<template>
  <view>
    <!-- 加入购物车弹窗 -->
    <u-popup
      :value="isShow"
      :mask-close-able="false"
      :border-radius="12"
      mode="bottom"
    >
      <view class="add-cart-view">
        <view class="close-icon"
          ><u-icon
            name="close"
            color="#666666"
            size="26"
            @click="closeaddcartPop"
          ></u-icon
        ></view>
        <view class="card-goods-info clearfix">
          <view class="float_left card-goods-img">
            <image
              v-if="now_sku_data.specImage"
              :src="now_sku_data.specImage"
              mode="aspectFill"
            ></image>
            <block v-else
              ><image
                v-if="goodsDetail.images"
                :src="goodsDetail.images[0]"
                mode="aspectFill"
              ></image
            ></block>
            <view v-if="goodsDetail.isEq === 5" class="Eq-view primary-bg"
              >抄码</view
            >
          </view>
          <view class="float_left" style="width: 420rpx">
            <view class="goods-title ellipsis">{{
              goodsDetail.title || ""
            }}</view>
            <!-- 不是阶梯价 -->
            <view
              class="card-goods-priceview primary-color"
              v-if="!now_sku_data.enabledLadder"
            >
              <text class="rmb-icon">¥</text>
              <text v-if="!showGoodsPrice">
                <block v-if="now_sku_data.id">{{
                  now_sku_data.salePrice || 0
                }}</block>
                <block v-else>{{
                  goodsDetail.isEq === 5
                    ? goodsDetail.maxSalePrice
                    : goodsDetail.minSalePrice
                }}</block>
              </text>
              <text v-else class="showGoodsPrice">{{ showGoodsPrice }}</text>
            </view>
            <!-- 阶梯价 -->
            <view class="lap-info clearfix" v-else>
              <view
                class="lap-li"
                v-for="(item, index) in now_sku_data.ladderPrice"
                :key="index"
              >
                <view class="laprice-text">
                  <span style="font-size: 20rpx">¥</span>
                  <text v-if="!showGoodsPrice">{{ item.price }}</text>
                  <text v-else class="showGoodsPrice">{{
                    showGoodsPrice
                  }}</text>
                </view>
                <view
                  class="laprice-goods-num"
                  v-if="index + 1 === now_sku_data.ladderPrice.length"
                  >≥{{ item.from }}{{ now_sku_data.unitName }}</view
                >
                <view class="laprice-goods-num" v-else
                  >{{ item.from }}~{{ item.to
                  }}{{ now_sku_data.unitName }}</view
                >
              </view>
            </view>
            <!-- 会员价 -->
            <block v-if="!showGoodsPrice">
              <view
                class="vip-price clearfix"
                v-if="goodsDetail.minMemberPrice > 0 && !now_sku_data.id"
              >
                <view class="price-text"
                  >¥{{
                    goodsDetail.isEq === 5
                      ? goodsDetail.maxMemberPrice
                      : goodsDetail.minMemberPrice
                  }}</view
                >
                <view class="price-bs">vip</view>
              </view>
              <block v-else>
                <view
                  class="vip-price clearfix"
                  v-if="now_sku_data.memberPrice > 0"
                >
                  <view class="price-text"
                    >¥{{ now_sku_data.memberPrice }}</view
                  >
                  <view class="price-bs">vip</view>
                </view>
              </block>
            </block>

            <view
              class="activity-tag"
              v-if="now_sku_data.isActivity && now_sku_data.isActivity === 5"
              >限时秒杀</view
            >
            <view class="card-goods-stock">
              <!-- 当前区域有库存 -->
              <block v-if="is_not_express">
                <!-- 选中规格 -->
                <block v-if="now_sku_data.id">
                  <view class="snum-li" v-if="baseSet.stockDisplay === 5">
                    库存：{{
                      now_sku_data.inventory >= 1 ||
                      goodsDetail.isDistribution === 5
                        ? "有货"
                        : "库存不足"
                    }}
                  </view>
                  <view class="snum-li" v-if="baseSet.stockDisplay === 6">
                    库存：
                    <text v-if="goodsDetail.isEq === 4">
                      {{
                        now_sku_data.inventory >= 1 ||
                        goodsDetail.isDistribution === 5
                          ? Math.floor(now_sku_data.inventory) || "有货"
                          : 0
                      }}
                    </text>
                    <text v-else>{{
                      now_sku_data.otherNum >= 1 ||
                      goodsDetail.isDistribution === 5
                        ? Math.floor(now_sku_data.otherNum) || "有货"
                        : 0
                    }}</text>
                  </view>
                </block>
                <!-- 未选中规格 -->
                <block v-else>
                  <view class="snum-li" v-if="baseSet.stockDisplay === 5">
                    库存：{{
                      goodsDetail.inventory >= 1 ||
                      goodsDetail.isDistribution === 5
                        ? "有货"
                        : "库存不足"
                    }}
                  </view>
                  <view class="snum-li" v-if="baseSet.stockDisplay === 6">
                    库存：
                    <text v-if="goodsDetail.isEq === 4">
                      {{
                        goodsDetail.inventory >= 1 ||
                        goodsDetail.isDistribution === 5
                          ? Math.floor(goodsDetail.inventory) || "有货"
                          : 0
                      }}
                    </text>
                    <text v-else>{{
                      goodsDetail.inventory >= 1 ||
                      goodsDetail.isDistribution === 5
                        ? Math.floor(goodsDetail.otherNum) || "有货"
                        : 0
                    }}</text>
                  </view>
                </block>
              </block>
              <!-- 当前区域没有库存 -->
              <block v-else>
                <view class="snum-li" v-if="baseSet.stockDisplay === 5"
                  >库存：库存不足</view
                >
                <view class="snum-li" v-if="baseSet.stockDisplay === 6"
                  >剩余 0</view
                >
              </block>
              <view class="snum-li"
                >起订{{ now_sku_data.setNum || 1
                }}{{
                  now_sku_data.unitName || goodsDetail.unitName || ""
                }}</view
              >
              <view class="snum-li" v-if="now_sku_data.limitNum"
                >限购{{ now_sku_data.limitNum
                }}{{ now_sku_data.unitName || goodsDetail.unitName }}</view
              >
            </view>
            <block v-for="(item, index) in goodsDetail.unitData" :key="index">
              <view v-if="item.isMaster === 4" class="card-goods-stock">
                <text v-if="goodsDetail.isEq === 5"
                  >1{{ item.unitName }}≈{{ item.conversion
                  }}{{ goodsDetail.unitName }}</text
                >
                <text v-else
                  >1{{ item.unitName }}={{ item.conversion
                  }}{{ goodsDetail.unitName }}</text
                >
                <text
                  style="margin-left: 10rpx"
                  v-if="
                    goodsDetail.showMinUnitPrice === 5 &&
                    now_sku_data.minUnitPrice !== '0.00'
                  "
                >
                  1斤={{
                    now_sku_data.minUnitPrice || goodsDetail.minMinUnitPrice
                  }}元
                </text>
              </view>
            </block>
            <view class="card-goods-unit" v-if="!now_sku_data.id">
              选择【单位】
              <block
                v-for="(item, index) in goodsDetail.specGroup"
                :key="index"
              >
                <text>【{{ item.groupSpec.specName }}】</text>
              </block>
            </view>
            <view class="card-goods-unit" v-else>
              已选：{{ buy_num }}{{ now_sku_data.unitName }}
              <text v-if="now_sku_data.specGroup.length > 0">，</text>
              <block
                v-for="(item, index) in now_sku_data.specGroup"
                :key="index"
              >
                <text>{{ item.specValueName }}</text>
                <text v-if="index !== now_sku_data.specGroup.length - 1"
                  >，</text
                >
              </block>

              <text v-if="goodsDetail.isEq === 5"
                >，{{ unitsalePrice }}元/{{ eq_sku_kg.unitName }}</text
              >
            </view>
          </view>
        </view>
        <!-- 配送地判断提醒 -->
        <view
          class="express-view"
          v-if="
            isLogin && address_data.provinceCode && not_dispatch_areas.areas
          "
          @click="
            goPage(
              '/pagesT/address/SelAddress?address_data=' +
                JSON.stringify(address_data)
            )
          "
        >
          <view class="express-tit">
            <text>送至</text>
            <text class="desc">(配送地可能会影响库存,请正确选择)</text>
          </view>
          <view class="region-view clearfix">
            <view class="float_left">
              <text class="ibonfont ibondizhi2"></text>
              <text
                >{{ address_data.provinceName }}-{{ address_data.cityName }}-{{
                  address_data.districtName
                }}</text
              >
            </view>
            <view class="float_right"
              ><text class="ibonfont ibonjinru"></text
            ></view>
          </view>
        </view>
        <scroll-view scroll-y class="spec-card-view">
          <view class="spec-card-li">
            <view class="spec-name">单位</view>
            <view class="spec-value-view">
              <block v-for="(item, index) in goodsDetail.unitData" :key="index">
                <!-- 抄码商品不显示主单位 -->
                <block
                  v-if="
                    item.isMaster !== 5 ||
                    (item.isMaster === 5 && goodsDetail.isEq !== 5)
                  "
                >
                  <view
                    class="spec-val-li"
                    @click="bindPickerChange(item.unitId, 1, '', item)"
                    :class="[
                      parseInt(spec_id_group[1]) === parseInt(item.unitId)
                        ? 'primary-bg spec-val-on'
                        : '',
                    ]"
                  >
                    <view v-if="!item.isdisabled" class="dis-tip">待补货</view>
                    <text :style="{ color: !item.isdisabled ? '#999' : '' }">{{
                      item.unitName
                    }}</text>
                  </view>
                </block>
              </block>
            </view>
          </view>
          <view
            class="spec-card-li"
            v-for="(item, index) in goodsDetail.specGroup"
            :key="index"
          >
            <view class="spec-name">{{ item.groupSpec.specName }}</view>
            <view class="spec-value-view">
              <block v-for="(itemP, indexP) in item.params" :key="indexP">
                <view
                  class="spec-val-li"
                  :class="[
                    parseInt(spec_id_group[index + 2]) ===
                    parseInt(itemP.specValueId)
                      ? 'primary-bg spec-val-on'
                      : '',
                  ]"
                  @click="
                    bindPickerChange(
                      itemP.specValueId,
                      index + 2,
                      item.groupSpec.specId,
                      itemP
                    )
                  "
                >
                  <view v-if="!itemP.isdisabled" class="dis-tip">待补货</view>
                  <text :style="{ color: !itemP.isdisabled ? '#999' : '' }">{{
                    itemP.specValueName
                  }}</text>
                </view>
              </block>
            </view>
          </view>
          <view class="buy-num-view clearfix">
            <view class="float_left">购买数量</view>
            <view
              class="num-edit-view float_right"
              v-if="goodsDetail.isDistribution === 4"
            >
              <view
                class="subr-view"
                :class="[
                  buy_num <= (now_sku_data.setNum || 1) ? 'disabled-color' : '',
                ]"
                @click="delNum"
              >
                <u-icon size="26" name="minus"></u-icon>
              </view>
              <view class="buy-num-input-view"
                ><input
                  @input="buyNumInput"
                  type="number"
                  :disabled="!now_sku_data.id"
                  cursor-spacing="25"
                  class="buy-num-input"
                  :value="buy_num"
              /></view>
              <view
                class="plus-view"
                :class="[
                  now_sku_data.limitNum
                    ? buy_num >= now_sku_data.limitNum
                      ? 'disabled-color'
                      : ''
                    : buy_num >= Math.floor(now_sku_data.inventory)
                    ? 'disabled-color'
                    : '',
                ]"
                @click="plusNum"
              >
                <u-icon size="26" name="plus"></u-icon>
              </view>
            </view>
            <view class="num-edit-view float_right" v-else>
              <view
                class="subr-view"
                :class="[
                  buy_num <= (now_sku_data.setNum || 1) ? 'disabled-color' : '',
                ]"
                @click="delNum"
              >
                <u-icon size="26" name="minus"></u-icon>
              </view>
              <view class="buy-num-input-view"
                ><input
                  @input="buyNumInput"
                  type="number"
                  :disabled="!now_sku_data.id"
				  cursor-spacing="25"
                  class="buy-num-input"
                  :value="buy_num"
              /></view>
              <view
                class="plus-view"
                :class="[
                  now_sku_data.limitNum
                    ? buy_num >= now_sku_data.limitNum
                      ? 'disabled-color'
                      : ''
                    : '',
                ]"
                @click="plusNum"
              >
                <u-icon size="26" name="plus"></u-icon>
              </view>
            </view>
          </view>
        </scroll-view>
        <view class="card-btn-view">
          <block
            v-if="
              goodsDetail.isDistribution === 4 && goodsDetail.inventorTotal <= 0
            "
          >
            <view
              v-if="
                !(goodsDetail.inventorTotal - 0) ||
                goodsDetail.inventorTotal - 0 <= 0
              "
              class="btn"
            >
              <view class="no-tip">抱歉，该商品在当前区域无库存</view>
            </view>
          </block>
          <!-- <view class="no-tip" v-if="!is_not_express">抱歉，该商品在当前区域无库存</view> -->
          <view class="buy-btn" v-else>
            <view
              @click="goodsBuyNow"
              class="card-btn-li primary-fu-bg"
              :class="[
                !is_not_express ||
                (goodsDetail.isDistribution === 4 &&
                  !Math.floor(now_sku_data.inventory))
                  ? 'dis-add'
                  : '',
              ]"
            >
              立即购买
            </view>
            <view
              @click="addCart"
              class="card-btn-li primary-bg"
              :class="[
                !is_not_express ||
                (goodsDetail.isDistribution === 4 &&
                  !Math.floor(now_sku_data.inventory))
                  ? 'dis-add'
                  : '',
              ]"
            >
              加入购物车
            </view>
          </view>
        </view>
      </view>
    </u-popup>

    <NoLoginTip @cancel="cancelTip" :show="loginTip" v-if="loginTip" />
  </view>
</template>

<script>
import NoLoginTip from "./NoLoginTip.vue";
export default {
  components: {
    NoLoginTip,
  },
  props: {
    selAddress: {
      type: Object,
      default: () => {
        return {};
      },
    },
    isShow: {
      type: Boolean,
      default: false,
    },
    goodsId: {
      type: [Number, String],
      default: 0,
    },
    isList: {
      type: Boolean,
      default: true,
    },
    skuId: {
      type: [Number, String],
      default: "",
    },
  },
  watch: {
    selAddress(val) {
      if (val.provinceCode) {
        this.address_data = val;
        if (this.not_dispatch_areas.areas) {
          if (this.address_data.districtCode) {
            this.is_not_express =
              this.not_dispatch_areas.areas.indexOf(
                parseInt(this.address_data.districtCode)
              ) === -1;
          } else if (this.address_data.cityCode) {
            this.is_not_express =
              this.not_dispatch_areas.citys.indexOf(
                parseInt(this.address_data.cityCode)
              ) === -1;
          } else {
            this.is_not_express =
              this.not_dispatch_areas.provinces.indexOf(
                parseInt(this.address_data.provinceCode)
              ) === -1;
          }
        }
      }
    },
    skuId(val) {
      if (this.goodsDetail.id) {
        const nowSkuData = this.goodsDetail.specMultiple.find(
          (item) => item.id === parseInt(val)
        );
        if (nowSkuData) {
          this.spec_id_group = nowSkuData.indexGroup.map((item) => {
            return parseInt(item);
          });
          this.buy_num = nowSkuData.setNum || 1;
          this.now_sku_data = nowSkuData;
        }
      }
    },
    now_sku_data(val) {
      this.$emit("skuChange", val);
    },
    goodsId(val) {
      if (this.isShow) {
        this.goodsDetail = {};
        this.now_sku_data = {};
        this.spec_id_group = [val];
        this.getGoodsDetail();
      }
    },
    async isShow(val) {
      if (val) {
        await this.SetShowGoodsPrice();
        if (!this.goodsDetail.id) {
          if (!this.isList) {
            this.goodsDetail = {};
            this.now_sku_data = {};
            this.spec_id_group = [this.goodsId];
            await this.getGoodsDetail();
          }
        }
        if (!this.address_data.provinceCode && this.isLogin) {
          await this.getAllShippingAddress();
        }
      } else {
        this.closeaddcartPop();
      }
    },
    buy_num(val) {
      this.$emit("buyNumchange", val);
    },
  },
  data() {
    return {
      eq_sku_kg: {},
      isLogin: true, // 判断是否登录
      loginTip: false,
      showGoodsPrice: "",
      goodsDetail: {
        images: [],
        specGroup: [],
        unitData: [],
      },
      spec_id_group: [],
      now_sku_data: {},
      buy_num: 1,
      now_sel_address: {},
      address_data: {}, // 客户地址数据
      not_dispatch_areas: {}, // 该商品不能配送区域
      is_not_express: true, // 当前选择区域是否能够配送
      activityId: "",
    };
  },
  computed: {
    baseSet() {
      return this.$store.state.baseSet;
    },
    // 起送价
    startDeliveryPrice() {
      return this.$store.state.baseSet.startDeliveryPrice || 0;
    },
    // 辅助单位价格
    unitsalePrice() {
      if (this.goodsDetail.isEq === 5) {
        if (this.eq_sku_kg.enabledLadder !== 1) {
          return this.eq_sku_kg.salePrice;
        } else {
          const unitnum = this.buy_num * Number(this.now_sku_data.conversion);
          const priceData = this.eq_sku_kg.ladderPrice.find((item) => {
            return unitnum > item.from && unitnum <= item.to;
          });
          return priceData.price;
        }
      } else {
        return this.eq_sku_kg.salePrice;
      }
    },
  },
  created() {
    this.spec_id_group[0] = this.goodsId;
    this.isLogin = this.$store.state.hasLogin;
    this.address_data = this.$store.state.nowAddress;
    if (this.address_data.provinceCode) {
      if (this.not_dispatch_areas.areas) {
        if (this.address_data.districtCode) {
          this.is_not_express =
            this.not_dispatch_areas.areas.indexOf(
              parseInt(this.address_data.districtCode)
            ) === -1;
        } else if (this.address_data.cityCode) {
          this.is_not_express =
            this.not_dispatch_areas.citys.indexOf(
              parseInt(this.address_data.cityCode)
            ) === -1;
        } else {
          this.is_not_express =
            this.not_dispatch_areas.provinces.indexOf(
              parseInt(this.address_data.provinceCode)
            ) === -1;
        }
      }
    }
  },
  methods: {
    // 商品立即购买
    goodsBuyNow() {
      if (!this.$store.state.hasLogin) {
        this.loginTip = true;
        this.closeaddcartPop();
        return;
      }
      if (!this.is_not_express) {
        return;
      }

      // 验证账户状态
      this.userAudit();
      if (!this.isUserAudit) {
        return;
      }

      if (!this.now_sku_data.id) {
        this.$api.msg("请选择商品属性");
        return;
      }
      if (
        this.goodsDetail.isDistribution === 4 &&
        !Math.floor(this.now_sku_data.inventory)
      ) {
        this.$api.msg("当前商品库存不足");
        return;
      }
      if (this.buy_num <= 0) {
        this.$api.msg("请输入大于0的购买数量");
        return;
      }
      if (this.buy_num < this.now_sku_data.setNum) {
        this.$api.msg(
          "该商品起订数量为" +
            this.now_sku_data.setNum +
            this.now_sku_data.unitName
        );
        return;
      }
      const totalPrice = this.$NP.times(
        this.now_sku_data.salePrice,
        this.buy_num
      );
      if (totalPrice < this.startDeliveryPrice) {
        this.$u.toast(
          "当前下单金额不足起送价：" +
            this.startDeliveryPrice +
            "元，先加入购物车吧"
        );
        return;
      }
      console.log(this.now_sku_data);
      if (this.now_sku_data.isActivity === 5) {
        this.activityId = this.now_sku_data.activity.activityId;
      }
      uni.navigateTo({
        url: `/pagesT/order/createOrder?goodsId=${this.goodsDetail.id}&goodsBasicId=${this.goodsDetail.basicGoodsId}&skuId=${this.now_sku_data.id}&buyNum=${this.buy_num}&shopId=${this.goodsDetail.shopId}&activityId=${this.activityId}`,
      });
    },
    cancelTip() {
      this.loginTip = false;
    },
    SetShowGoodsPrice() {
      if (
        this.$store.state.baseSet.goodsPrice === 5 &&
        this.$store.state.hasLogin
      ) {
        this.showGoodsPrice = "";
      } else if (
        !this.$store.state.hasLogin &&
        this.$store.state.baseSet.goodsPrice === 4
      ) {
        this.showGoodsPrice = "¥**";
      } else if (
        this.$store.state.userStatus.enableStatus === 4 &&
        this.$store.state.baseSet.goodsPrice === 4
      ) {
        this.showGoodsPrice = "已禁用";
      } else if (
        this.$store.state.userStatus.status !== 2 &&
        this.$store.state.baseSet.goodsPrice === 4
      ) {
        if (this.$store.state.userStatus.status === 0) {
          this.showGoodsPrice = "待审核";
        } else if (this.$store.state.userStatus.status === 1) {
          this.showGoodsPrice = "审核中";
        } else if (this.$store.state.userStatus.status === 3) {
          this.showGoodsPrice = "已驳回";
        }
      } else {
        this.showGoodsPrice = "";
      }
    },
    delNum() {
      if (!this.now_sku_data.id) {
        this.$api.msg("请选择商品属性");
        return;
      }
      // 不支持负库存销售
      if (this.goodsDetail.isDistribution === 4) {
        if (this.buy_num > Math.floor(this.now_sku_data.inventory)) {
          this.buy_num =
            Math.floor(this.now_sku_data.inventory) < 0
              ? 0
              : Math.floor(this.now_sku_data.inventory);
          return;
        }
      }

      if (this.now_sku_data.cartNum > 0) {
        if (this.buy_num > 1) {
          this.buy_num = this.buy_num - 1;
        } else {
          this.$api.msg("不能再减少了哦！");
        }
      } else {
        // this.$api.msg('不能再减少了哦！')
        if (this.buy_num > this.now_sku_data.setNum) {
          this.buy_num = this.buy_num - 1;
        } else {
          this.$api.msg("不能再减少了哦！");
        }
      }
    },
    plusNum() {
      if (!this.now_sku_data.id) {
        this.$api.msg("请选择商品属性");
        return;
      }
      if (this.now_sku_data.limitNum > 0) {
        if (this.buy_num >= this.now_sku_data.limitNum) {
          // this.$api.msg(`限购${this.now_sku_data.limitNum}${this.now_sku_data.unitName}，不能再增加了哦！`);
          return;
        }
      }
      if (this.goodsDetail.isDistribution === 4) {
        if (this.buy_num >= Math.floor(this.now_sku_data.inventory)) {
          // this.$api.msg('不能再增加了哦！');
          return;
        }
      }

      this.buy_num = this.buy_num - 0 + 1;
    },
    buyNumInput(e) {
      // 当重复设置某些属性为相同的值时，不会同步到view层。解决方法，在设置新值之前先设置为记录的当前值
      this.buy_num = e.detail.value - 0;
      // 没有启用预售不用检查库存
      if (this.goodsDetail.isDistribution === 4) {
        if (e.detail.value - 0 > Math.floor(this.now_sku_data.inventory)) {
          this.$api.msg("库存不足，已为您修正");
          this.$nextTick(() => {
            this.buy_num = Math.floor(this.now_sku_data.inventory);
          });
          return;
        }
      }

      if (this.now_sku_data.limitNum) {
        if (e.detail.value - 0 > this.now_sku_data.limitNum) {
          this.$api.msg(
            `限购${this.now_sku_data.limitNum}${this.now_sku_data.unitName}，已为您修正`
          );
          this.$nextTick(() => {
            this.buy_num = Math.floor(this.now_sku_data.limitNum);
          });
        } else if (e.detail.value - 0 < this.now_sku_data.limitNum) {
          // 当起订数量小于限购数量莳
          if (
            this.now_sku_data.setNum &&
            this.now_sku_data.setNum <= this.now_sku_data.limitNum
          ) {
            // 当存在起订数量
            // if (e.detail.value - 0 < this.now_sku_data.setNum) {
            // 	this.$api.msg('该商品起订数量为' + this.now_sku_data.setNum + this.now_sku_data.unitName);
            // 	this.$nextTick(() => {
            // 		this.buy_num = this.now_sku_data.setNum;
            // 	});
            // }
          } else if (
            this.now_sku_data.setNum &&
            this.now_sku_data.setNum > this.now_sku_data.limitNum
          ) {
            // 当存在起订数量
            if (e.detail.value - 0 < this.now_sku_data.limitNum) {
              this.$api.msg(
                `限购${this.now_sku_data.limitNum}${this.now_sku_data.unitName}，已为您修正`
              );
              this.$nextTick(() => {
                this.buy_num = Math.floor(this.now_sku_data.limitNum);
              });
            }
          } else {
            this.$nextTick(() => {
              this.buy_num = this.now_sku_data.setNum || e.detail.value - 0;
            });
          }
        }
      } else {
        // 没有启用预售不用检查库存
        if (this.goodsDetail.isDistribution === 4) {
          if (e.detail.value - 0 > Math.floor(this.now_sku_data.inventory)) {
            this.$api.msg("库存不足，已为您修正");
            this.$nextTick(() => {
              this.buy_num = Math.floor(this.now_sku_data.inventory);
            });
          }
        }
      }
    },
    // 关闭加入购物车弹窗
    closeaddcartPop() {
      this.$emit("close", false);
    },
    /*
     *选择规格
     * id 单位属性的ID
     * index 规格id组的下标
     * specId 属性名id
     * row 当前选中属性值
     */
    bindPickerChange(id, index, specId, row) {
      // 判断当前规格是否禁用
      if (row && !row.isdisabled) {
        return;
      }
      this.$set(this.spec_id_group, index, parseInt(id));
      if (this.spec_id_group.every((item) => !!item)) {
        const indexGroup = this.spec_id_group.join(":");
        const nowSkuData = this.goodsDetail.specMultiple.find(
          (item) => item.index === indexGroup
        );
        if (nowSkuData) {
          this.now_sku_data = nowSkuData;
        }
      }
      // this.buy_num = this.now_sku_data.setNum || 1;
      if (
        this.now_sku_data.limitNum > 0 &&
        this.now_sku_data.setNum > this.now_sku_data.limitNum
      ) {
        this.buy_num = this.now_sku_data.limitNum || 1;
      } else {
        this.buy_num = this.now_sku_data.setNum || 1;
      }
      // 判断当前规格是否要禁用，规格组不存在或者库存为0的时候，当前规格禁用
      if (index) {
        // 过滤出包含当前规格的规格组
        const containSpecMultiple = this.goodsDetail.specMultiple.filter(
          (item) => item.indexGroup.includes(id + "")
        );
        const target = this.$u.deepClone(this.goodsDetail.specGroup);
        target.forEach((item) => {
          if (item.groupSpec.specId !== specId) {
            item.params.forEach((itemP) => {
              const isObj = containSpecMultiple.find((itemF) => {
                return itemF.indexGroup.includes(itemP.specValueId + "");
              });
              // 没有开启预售判断库存
              if (this.goodsDetail.isDistribution === 4) {
                itemP.isdisabled =
                  !!isObj &&
                  Math.floor(isObj.inventory) > 0 &&
                  isObj.isSale !== 4;
              } else {
                itemP.isdisabled = isObj.isSale !== 4;
              }
            });
          }
        });
        this.goodsDetail.specGroup = target;
      }
    },
    // 加入购物车
    async addCart() {
      if (!this.$store.state.hasLogin) {
        this.loginTip = true;
        this.closeaddcartPop();
        return;
      }
      if (!this.is_not_express) {
        return;
      }
      // 验证账户状态
      this.userAudit();
      if (!this.isUserAudit) {
        return;
      }

      if (!this.now_sku_data.id) {
        this.$api.msg("请选择商品属性");
        return;
      }
      if (
        this.goodsDetail.isDistribution === 4 &&
        !Math.floor(this.now_sku_data.inventory)
      ) {
        this.$api.msg("当前商品库存不足");
        return;
      }
      if (this.buy_num <= 0) {
        this.$api.msg("请输入大于0的购买数量");
        return;
      }
      if (this.buy_num < this.now_sku_data.setNum) {
        this.$api.msg(
          "该商品起订数量为" +
            this.now_sku_data.setNum +
            this.now_sku_data.unitName
        );
        return;
      }
      const goodsData = [
        {
          goodsBasicId: this.goodsDetail.basicGoodsId,
          goodsId: this.goodsDetail.id,
          buyNum: this.buy_num,
          shopId: this.goodsDetail.shopId,
          source: this.$common.source(),
          skuId: this.now_sku_data.id,
        },
      ];
      this.$u.api
        .addCart({
          goodsData,
        })
        .then((res) => {
          uni.showToast({
            title: "加入成功",
            icon: "none",
          });

          let stateNum = this.$_utils.accAdd(
            (this.$store.state.cartNum || 0) - 0,
            this.buy_num
          );
          let statePrice = this.$_utils.accAdd(
            (this.$store.state.cartPrice || 0) - 0,
            (this.now_sku_data.salePrice - 0) * this.buy_num
          );

          this.$store.commit("commit_cartNum", stateNum);
          this.$store.commit("commit_cartPrice", statePrice);
          this.closeaddcartPop();
          // 点击购物车发送请求
          // setTimeout(() => {
          // 	uni.switchTab({
          // 		url: '/pages/cart/cart'
          // 	});
          // }, 100)
        });
    },
    // 请求商品品详情
    async getGoodsDetail() {
      this.$u.api
        .getGoodsDetail(this.goodsId)
        .then(({ data }) => {
          this.goodsDetail = data;
          // 抄码商品获取 KG 数据
          if (data.isEq === 5) {
            this.eq_sku_kg = data.specMultiple.find(
              (item) => item.isMaster === 5
            );
          }
          this.buy_num = 1;
          // 多规格时处理属性禁用标示
          if (data.specType !== 1) {
            data.specGroup = data.specGroup.map((item) => {
              return {
                ...item,
                params: item.params.map((itemP) => {
                  return {
                    ...itemP,
                    isdisabled: true,
                  };
                }),
              };
            });
            data.unitData.forEach((item) => {
              item.isdisabled = true;
            });
          } else {
            //单规格 添加当前单位没有库存的标记
            const arr = data.specMultiple.filter(
              (item) => Math.floor(item.inventory) <= 0
            );
            data.unitData.forEach((item) => {
              const unitItem = data.specMultiple.find(
                (itemF) => itemF.unitId === item.unitId
              );
              // 没有开启预售判断库存
              if (this.goodsDetail.isDistribution === 4) {
                item.isdisabled =
                  Math.floor(unitItem.inventory) > 0 && unitItem.isSale !== 4;
              } else {
                item.isdisabled = unitItem.isSale !== 4;
              }
            });
          }

          if (this.skuId) {
            // 如果已有选中的skuId 根据ID匹配对应规格数据
            const specMultiple = data.specMultiple.find(
              (item) => item.id === parseInt(this.skuId)
            );
            if (specMultiple.isSale !== 4) {
              this.now_sku_data = specMultiple;
            }
          } else if (data.specMultiple.length === 1) {
            //当规格只有一个默认选中
            // 没有开启预售
            if (data.specMultiple[0].isSale !== 4) {
              if (this.goodsDetail.isDistribution === 4) {
                // 如果当前商品规格只有一个且库存大于0则默认选中
                if (
                  data.specMultiple[0].inventory > 0 &&
                  data.specMultiple[0].isSale !== 4
                ) {
                  this.now_sku_data = data.specMultiple[0];
                }
              } else {
                this.now_sku_data = data.specMultiple[0];
              }
            }
          } else {
            // 如果当前商品是非抄码商品 默认选中默认规格
            if (data.isEq === 4) {
              const specMultiple = data.specMultiple.find(
                (item) => item.isDefault === 5
              );
              if (specMultiple && specMultiple.isSale !== 4) {
                this.now_sku_data = specMultiple;
              }
            } else {
              // 抄码商品默认选中一个
              const specMultiple = data.specMultiple.find(
                (item) => item.isMaster === 4
              );
              if (specMultiple && specMultiple.isSale !== 4) {
                this.now_sku_data = specMultiple;
              }
            }
          }
          // 如果有已选中的规格则进行下一步规格的操作处理
          // console.log(this.goodsDetail);
          if (!this.now_sku_data.id) {
            return;
          }
          // 进行组合选中规格的id数组
          this.spec_id_group = this.now_sku_data.indexGroup.map((item) => {
            return parseInt(item);
          });
          //如果起订数量大于限购数量，默认购买数量为限购数量
          if (
            this.now_sku_data.limitNum > 0 &&
            this.now_sku_data.setNum > this.now_sku_data.limitNum
          ) {
            this.buy_num = this.now_sku_data.limitNum || 1;
          } else {
            // 否则购买数量为起订数量
            this.buy_num = this.now_sku_data.setNum || 1;
          }
          // 该商品不能配送区域
          this.not_dispatch_areas = data.express.ruleData.not_dispatch_areas;
          //  默认设置当前选择区域是否能够配送的标示为true
          this.is_not_express = true;
          this.$nextTick(() => {
            if (this.not_dispatch_areas.areas) {
              if (this.address_data.districtCode) {
                this.is_not_express =
                  this.not_dispatch_areas.areas.indexOf(
                    parseInt(this.address_data.districtCode)
                  ) === -1;
              } else if (this.address_data.cityCode) {
                this.is_not_express =
                  this.not_dispatch_areas.citys.indexOf(
                    parseInt(this.address_data.cityCode)
                  ) === -1;
              } else {
                this.is_not_express =
                  this.not_dispatch_areas.provinces.indexOf(
                    parseInt(this.address_data.provinceCode)
                  ) === -1;
              }
            }
          });
        })
        .catch((err) => {
          this.closeaddcartPop();
        });
    },
    // 获取地址列表
    async getAllShippingAddress() {
      this.$u.api
        .getAllShippingAddress({
          page: 1,
          pageSize: 10,
        })
        .then(({ data }) => {
          if (data.length) {
            const address =
              data.find((item) => item.defaultStatus === 5) || data[0];
            this.address_data = {
              provinceCode: address.provinceCode,
              cityCode: address.cityCode,
              districtCode: address.districtCode,
              provinceName: address.area.provinceName,
              cityName: address.area.cityName,
              districtName: address.area.districtName,
            };
            this.$store.commit("commit_nowAddress", this.address_data);
            if (this.not_dispatch_areas.areas) {
              if (this.address_data.districtCode) {
                this.is_not_express =
                  this.not_dispatch_areas.areas.indexOf(
                    parseInt(this.address_data.districtCode)
                  ) === -1;
              } else if (this.address_data.cityCode) {
                this.is_not_express =
                  this.not_dispatch_areas.citys.indexOf(
                    parseInt(this.address_data.cityCode)
                  ) === -1;
              } else {
                this.is_not_express =
                  this.not_dispatch_areas.provinces.indexOf(
                    parseInt(this.address_data.provinceCode)
                  ) === -1;
              }
            }
          }
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.activity-tag {
  font-size: 20upx;
  padding: 2upx 4upx;
  background-color: #ff4d01;
  color: #fff;
  border-radius: 4upx;
  display: inline-block;
}

.add-cart-view {
  position: relative;
  background-color: #fff;
  padding: 30upx;
  border-top-left-radius: 8upx;
  border-top-right-radius: 8upx;

  .close-icon {
    position: absolute;
    top: 20upx;
    right: 20upx;
  }

  .card-goods-info {
    .card-goods-img {
      padding-right: 32upx;
      position: relative;
      overflow: hidden;

      image {
        border-radius: 8upx;
        width: 230upx;
        height: 230upx;
        display: block;
      }

      .Eq-view {
        width: 140rpx;
        background-color: $uni-color-primary;
        color: #ffffff;
        position: absolute;
        left: -40rpx;
        top: 14rpx;
        transform: rotate(-45deg);
        font-size: 20rpx;
        text-align: center;
        line-height: 30rpx;
      }
    }

    .goods-title {
      font-weight: 600;
      -webkit-line-clamp: 1;
    }

    .lap-info {
      display: flex;
      font-size: 24upx;

      .lap-li {
        text-align: center;
        flex: 3;
        padding: 0 20upx;

        .laprice-text {
          font-size: 28upx;
          font-weight: 600;
          color: #ff4d01;
          font-family: DIN-Medium;
        }
      }
    }

    .card-goods-priceview {
      color: #ff4d01;
      font-weight: 600;
      font-size: 40upx;
      padding-top: 16upx;
      font-family: DIN-Medium;

      .rmb-icon {
        font-weight: 400;
        margin-right: 8upx;
        font-size: 24upx;
      }
    }

    .card-goods-stock {
      font-size: 24upx;
      color: #999999;
      padding-top: 10upx;

      .snum-li {
        padding-right: 10upx;
        display: inline-block;

        &:last-child-child {
          padding-right: 0;
        }
      }
    }

    .card-goods-unit {
      font-size: 24upx;
      padding-top: 10upx;
    }
  }

  .spec-card-view {
    max-height: 700upx;
    overflow-y: auto;

    .spec-card-li {
      padding: 20upx 0 0;
      border-bottom: 1px solid #f5f5f5;

      .spec-name {
        font-size: 28upx;
        padding-bottom: 20upx;
      }

      .spec-value-view {
        .spec-val-li {
          margin-right: 30upx;
          margin-bottom: 18upx;
          border-radius: 8upx;
          font-size: 26upx;
          display: inline-block;
          min-width: 52upx;
          padding: 0 24upx;
          line-height: 54upx;
          text-align: center;
          color: #333333;
          border: 1px solid #eeeeee;
          background-color: #eeeeee;
          position: relative;

          .dis-tip {
            position: absolute;
            font-size: 18rpx;
            color: #ffffff;
            background-color: #c0c4cc;
            padding: 4rpx 6rpx;
            border-top-left-radius: 12rpx;
            border-bottom-right-radius: 12rpx;
            top: -20rpx;
            right: -30rpx;
            line-height: 20rpx;
          }
        }

        .spec-val-on {
          background-color: $uni-color-primary;
          color: #ffffff;
        }
      }
    }
  }

  .buy-num-view {
    padding: 20upx 0 130upx;
    font-size: 28upx;

    .num-edit-view {
      text-align: center;
      display: inline-flex;
      align-items: center;

      .buy-num-input-view {
        display: flex;
        position: relative;
        text-align: center;
        padding: 0;
        justify-content: center;
        align-items: center;
        margin: 0 6rpx;
        flex-direction: row;

        .buy-num-input {
          width: 80upx;
          text-align: center;
          line-height: 44upx;
          height: 44upx;
          font-size: 26upx;
        }
      }

      .subr-view,
      .plus-view {
        justify-content: center;
        align-items: center;
        flex-direction: row;
        display: flex;
        margin-top: 0upx;
        width: 44upx;
        height: 44upx;
        background-color: #f2f3f5;
        font-size: 36upx;
        color: #323233;
        border-radius: 8upx;
      }

      .disabled-color {
        color: #c8c9cc;
        background: #f7f8fa;
      }
    }
  }

  .card-btn-view {
    position: absolute;
    bottom: 0;
    left: 0;
    z-index: 9;
    width: 750upx;
    background-color: #fff;
    border-top: 1px solid #f5f5f5;

    .no-tip {
      font-size: 22upx;
      background-color: #fdf6ec;
      color: #d48d24;
      text-align: center;
      line-height: 42upx;
    }

    .buy-btn {
      display: flex;

      .card-btn-li {
        flex: 2;
        // width: 100%;
        text-align: center;
        line-height: 90upx;
        color: #fff;
        background-color: #007aff;
      }

      .dis-add {
        color: #cccccc;
      }
    }
  }
}

.express-view {
  padding: 20upx 0;
  border-bottom: 1px solid #f5f5f5;

  .express-tit {
    font-size: 28upx;
    padding-bottom: 10upx;

    .desc {
      font-size: 20upx;
      color: #999999;
    }
  }

  .region-view {
    font-size: 26upx;

    .float_left {
      .ibondizhi2 {
        font-size: 28upx;
        margin-right: 10upx;
        color: #666666;
      }
    }

    .float_right {
      .ibonjinru {
        font-size: 28upx;
        color: #666666;
      }
    }
  }
}

.vip-price {
  margin-top: 6rpx;
  line-height: 32rpx;
  height: 32rpx;
  border-radius: 3rpx;
  overflow: hidden;
  font-family: DINPro-Regular;

  .price-text {
    float: left;
    min-width: 80rpx;
    text-align: center;
    vertical-align: middle;
    font-size: 20rpx;
    color: #ffdfa2;
    background: linear-gradient(270deg, #1e5657 0%, #0d2b2c 100%);
    padding: 0 8rpx;
  }

  .price-bs {
    text-align: center;
    float: left;
    vertical-align: middle;
    width: 32rpx;
    background-color: #ffdfa2;
    font-size: 20rpx;
    color: #2c7564;
  }
}
</style>
